package com.digitalbuana.smiles.activity;

import java.util.Collection;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.digitalbuana.smiles.R;
import com.digitalbuana.smiles.data.ActivityManager;
import com.digitalbuana.smiles.data.Application;
import com.digitalbuana.smiles.data.account.OnAccountChangedListener;
import com.digitalbuana.smiles.service.SmilesService;
import com.digitalbuana.smiles.ui.helper.SingleActivity;
import com.digitalbuana.smiles.utils.FontUtils;

public class SplashActivity extends SingleActivity implements
OnAccountChangedListener
{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		
		//Casting
		rootView = (FrameLayout)findViewById(R.id.splashRootView);
		FontUtils.setNormalRobotoFont(context, rootView);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Application.getInstance().addUIListener(OnAccountChangedListener.class,this);
		if (Application.getInstance().isClosing()) {
			((TextView) findViewById(R.id.text)).setText(R.string.application_state_closing);
		} else {
			startService(SmilesService.createIntent(this));
			update();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		Application.getInstance().removeUIListener(OnAccountChangedListener.class, this);
	}

	@Override
	public void onAccountsChanged(Collection<String> accounts) {
		update();
	}
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			cancel();
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void update() {
		
		if (Application.getInstance().isInitialized()&& !Application.getInstance().isClosing() && !isFinishing()) {
			finish();
		}
	}

	private void cancel() {
		finish();
		ActivityManager.getInstance().cancelTask(this);
	}

	public static Intent createIntent(Context context) {
		return new Intent(context, SplashActivity.class);
	}

}
